package com.micro.form;

import com.micro.download.MyThreadFactory;
import com.micro.global.ConfigInfo;
import com.micro.global.MainTaskTreadPool;
import com.micro.global.TaskInfoDataBase;
import com.micro.utils.SeriaUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author dufen
 */
public class MainForm extends Application {

    private static Stage stage1 = new Stage(StageStyle.DECORATED);
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1), new MyThreadFactory("monitor-group", "monitor-thread"));
    private static boolean isClose = false;

    static {
        try {
            Scene scene = new Scene(loadFXML("MainForm"));
            stage1.setScene(scene);
            stage1.setTitle("M3u8Download Beta v" + ConfigInfo.VERSION);
            InputStream inputStream = MainForm.class.getResourceAsStream("MainForm.png");
            javafx.scene.image.Image image = new javafx.scene.image.Image(inputStream);
            stage1.getIcons().add(image);
            stage1.setOnCloseRequest((event) -> {

            });

            //设置关闭窗口时该做的事情，完成后退出所有进程
            Platform.setImplicitExit(false);
            stage1.setResizable(false);
            tray();
            threadPoolExecutor.submit(() -> {
                setClose();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setClose() {
        AtomicBoolean flag = new AtomicBoolean(false);
        while (true) {
            if (isClose) {
                TaskInfoDataBase.DOWNLOADING_M3U8.forEach((k, v) -> {
                    if (v.isTerminated()) {
                        flag.set(true);
                    } else {
                        v.close();
                    }
                });

                if (flag.get()) {
                    break;
                }
                MainTaskTreadPool.getINSTANCE().shutdownNow();
            }
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        SeriaUtil.writeData();
    }


    public static void hide() {
        stage1.hide();
    }

    public static void show() {
        stage1.show();
    }

    public static boolean isShow() {
        return stage1.isShowing();
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(MainForm.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    /**
     * 托盘
     */
    public static void tray() {
        if (SystemTray.isSupported()) {
            try {
                URL in = MainForm.class.getResource("MainForm.png");
                Image image = ImageIO.read(in);
                PopupMenu popupMenu = new PopupMenu();
                MenuItem showOrHideMenu = new MenuItem("显示/隐藏");
                showOrHideMenu.setFont(new Font("黑体", Font.BOLD, 12));
                MenuItem exitMenu = new MenuItem("退出");
                exitMenu.setFont(new Font("黑体", Font.BOLD, 12));
                popupMenu.add(showOrHideMenu);
                popupMenu.add(exitMenu);
                showOrHideMenu.addActionListener((event) -> {
                    Platform.runLater(() -> {
                        if (stage1.isShowing()) {
                            stage1.hide();
                        } else {
                            stage1.show();
                        }
                    });
                });
                exitMenu.addActionListener(e -> {
                    SeriaUtil.writeData();
                    //退出所有进程
                    System.exit(0);
                });
                TrayIcon trayIcon = new TrayIcon(image, "M3u8Download Beta v" + ConfigInfo.VERSION, popupMenu);
                trayIcon.setPopupMenu(popupMenu);
                trayIcon.setImageAutoSize(true);
                trayIcon.addActionListener((event) -> {
                    Platform.runLater(() -> {
                        if (stage1.isShowing()) {
                            stage1.hide();
                        } else {
                            stage1.show();
                        }
                    });
                });
                SystemTray.getSystemTray().add(trayIcon);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void start(Stage stage) throws IOException {
        stage = stage1;
        stage.show();
    }
}
